<template>
  <div class="workDetail">
    <el-tabs
      v-model="activeName"
      class="workDetail-tabs"
      tab-position="bottom"
      type="border-card"
      @tab-change="handleChangeTab"
    >
      <el-tab-pane label="业务表单" name="businness">
        <component
          :is="isComponent"
          v-if="taskRouteData.businessId"
          :id="taskRouteData.businessId"
          ref="chindRef"
          v-bind="$props"
        >
          <el-button
            v-if="copyId"
            icon="chatLineRound"
            plain
            type="primary"
            @click="handleReply('reply', null)"
            >回复
          </el-button>
          <el-button
            v-if="processed"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('agree')"
            >{{ returnTaskList.length == 0 ? '提交' : '同意' }}
          </el-button>
          <!-- 是否办结 -->
          <el-button
            v-if="processed && completion"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('completion')"
            >{{ completion }}1
          </el-button>
          <!-- 走其他人审批 ：如提交总经理审批 -->
          <el-button
            v-if="processed && otherApprovals"
            icon="el-icon-circle-check"
            plain
            type="primary"
            @click="handleComplete('otherApprovals')"
            >{{ otherApprovals }}
          </el-button>
          <!-- <el-button
                                                                                                                                                                            icon="el-icon-chat-line-square"
                                                                                                                                                                            type="primary"
                                                                                                                                                                            @click="handleDelegate"
                                                                                                                                                                            >委派</el-button
                                                                                                                                                                          >
                                                                                                                                                                          <el-button icon="el-icon-thumb" type="success" @click="handleTransfer"
                                                                                                                                                                            >转办</el-button
                                                                                                                                                                          > -->
          <el-button
            v-if="processed && returnTaskList.length != 0"
            icon="el-icon-refresh-left"
            plain
            type="primary"
            @click="handleReturn"
            >不同意
          </el-button>
          <el-button
            v-if="processed && returnTaskList.length != 0 && !signDisabled"
            icon="operation"
            plain
            type="primary"
            @click="handleCountersign"
            >加签
          </el-button>
          <!-- <el-button
                                                                                                                                                                            icon="el-icon-circle-close"
                                                                                                                                                                            type="primary"
                                                                                                                                                                            plain
                                                                                                                                                                            @click="handleReject"
                                                                                                                                                                            v-if="processed"
                                                                                                                                                                            >拒绝</el-button
                                                                                                                                                                          > -->
          <el-button
            v-if="isCirculation"
            icon="Document"
            plain
            type="primary"
            @click="handleComplete('circulation')"
            >传阅
          </el-button>
        </component>
      </el-tab-pane>
      <el-tab-pane label="查看意见" name="record">
        <el-switch
          v-model="orderReverse"
          active-text="时间倒序"
          class="mt-10px ml-20px"
          inactive-color="#1890ff"
          inactive-text="时间正序"
          inline-prompt
          @change="orderReverseFn"
        />
        <el-card class="box-card" shadow="never">
          <el-col :offset="2" :span="20">
            <!--  流程环节中-->
            <div ref="eleRefs" class="block pb-20px">
              <el-timeline>
                <el-timeline-item
                  v-for="(item, index) in historyProcNodeList"
                  :key="index"
                  :color="setColor(item.endTime)"
                  :icon="setIcon(item.endTime)"
                >
                  <div class="mb-10px relative">
                    <label>{{ item.activityName }}</label>
                    <span
                      v-if="item.activityType === 'userTask'"
                      class="ml-10px"
                      >{{ item.assigneeName }}</span
                    >
                    <span
                      v-if="item.activityType === 'userTask'"
                      class="ml-10px"
                      >{{ item.endTime }}</span
                    >
                    <!-- 审批状态 -->
                    <div
                      v-if="item.commentList && item.commentList.length > 0"
                      class="inline-block ml-10px"
                    >
                      <div
                        v-for="(comment, index) in item.commentList"
                        :key="index"
                      >
                        <el-tag
                          v-if="comment.type != 8"
                          :type="approveTypeTag(comment.type)"
                          >{{ commentType(comment.type) }}
                        </el-tag>
                      </div>
                    </div>
                    <span
                      v-if="item.activityType === 'userTask' && item.copyName"
                      class="ml-110px"
                      >抄送：{{ item.copyName }}</span
                    >
                    <el-button
                      class="ml-30px"
                      icon="chatLineRound"
                      plain
                      size="small"
                      style="position: absolute; top: 0; right: 0"
                      type="primary"
                      @click="handleReply('flowReply', item)"
                      >回复
                    </el-button>
                  </div>
                  <el-card
                    v-if="item.activityType === 'startEvent'"
                    class="box-card"
                    shadow="hover"
                  >
                    {{ item.assigneeName }} 在 {{ item.createTime }} 发起流程
                  </el-card>
                  <el-card
                    v-if="
                      (item.activityType === 'userTask' &&
                        item.commentList &&
                        item.commentList.length > 0) ||
                      (item.activityType === 'userTask' &&
                        item.attachmentList &&
                        item.attachmentList.length > 0)
                    "
                    class="box-card bg-#f7fbfe ss"
                    shadow="hover"
                  >
                    <!-- <el-descriptions
                                                                                                                                                                                                                                                                                                                                                        :column="5"
                                                                                                                                                                                                                                                                                                                                                        :labelStyle="{ 'font-weight': 'bold' }"
                                                                                                                                                                                                                                                                                                                                                      >
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="实际办理：">{{
                                                                                                                                                                                                                                                                                                                                                          item.assigneeName || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="候选办理：">{{
                                                                                                                                                                                                                                                                                                                                                          item.candidate || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="抄送：">{{
                                                                                                                                                                                                                                                                                                                                                          item.copyName || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="接收时间：">{{
                                                                                                                                                                                                                                                                                                                                                          item.createTime || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="办结时间：">{{
                                                                                                                                                                                                                                                                                                                                                          item.endTime || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                        <el-descriptions-item label="耗时：">{{
                                                                                                                                                                                                                                                                                                                                                          item.duration || '-'
                                                                                                                                                                                                                                                                                                                                                        }}</el-descriptions-item>
                                                                                                                                                                                                                                                                                                                                                      </el-descriptions> -->
                    <!-- 状态，建议 -->
                    <div v-if="item.commentList && item.commentList.length > 0">
                      <div
                        v-for="(comment, index) in item.commentList"
                        :key="index"
                      >
                        <span>{{ comment.fullMessage }}</span>
                      </div>
                    </div>

                    <!-- 附件 -->
                    <div
                      v-if="
                        item.attachmentList && item.attachmentList.length > 0
                      "
                      class="mt-10px"
                    >
                      <span class="text-#1890ff">附件：</span>
                      <div
                        v-for="item in item.attachmentList"
                        :key="item.id"
                        class="inline-block"
                      >
                        <a
                          :href="item.url"
                          class="ml-10px text-#1890ff"
                          target="_blank"
                          >{{ item.name }}</a
                        >
                      </div>
                    </div>
                  </el-card>
                  <!-- 抄送人回复的内容 -->
                  <el-card
                    v-if="
                      item.activityType === 'userTask' &&
                      item.copyCommentList &&
                      item.copyCommentList.length > 0
                    "
                    class="box-card bg-#f7fbfe ss"
                    shadow="hover"
                  >
                    <div
                      v-for="(copyItem, index) in item.copyCommentList"
                      :key="index + 'i'"
                    >
                      <p class="m-0">
                        <span class="text-#000">{{ copyItem.userName }}</span>
                        <span class="ml-10px">{{ copyItem.time }}</span>
                      </p>
                      <p class="mt-10px">{{ copyItem.comment }}</p>
                      <!-- 附件 -->
                      <div
                        v-if="
                          copyItem.attachmentList &&
                          copyItem.attachmentList.length > 0
                        "
                        class="my-10px"
                      >
                        <span class="text-#1890ff">附件：</span>
                        <div
                          v-for="item in copyItem.attachmentList"
                          :key="item.id"
                          class="inline-block"
                        >
                          <a
                            :href="item.url"
                            class="ml-10px text-#1890ff"
                            target="_blank"
                            >{{ item.name }}</a
                          >
                        </div>
                      </div>
                    </div>
                  </el-card>
                  <el-card
                    v-if="item.activityType === 'endEvent'"
                    class="box-card"
                    shadow="hover"
                  >
                    {{ item.createTime }} 结束流程
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
            <!-- 传阅-->
            <el-collapse class="mt--20px relative">
              <div style="position: absolute; top: 12px; right: 26px">
                <el-button
                  class="ml-30px"
                  icon="chatLineRound"
                  plain
                  size="small"
                  type="primary"
                  @click="handleReply('flowReply', null)"
                  >回复
                </el-button>
              </div>
              <el-collapse-item
                :title="`查看回复(${replyList.length})`"
                name="reply"
              >
                <div
                  class="block mt-10px mb-20px bg-#f7fbfe p-20px pt-10px ml-40px"
                >
                  <div
                    v-for="(activity, index) in replyList"
                    :key="index"
                    class="pt-10px relative"
                  >
                    <div>
                      <span class="text-#303133 font-bold mr-10px">{{
                        activity.sendName
                      }}</span>
                      <span v-if="activity.recvName"> 回复</span>
                      <span
                        v-if="activity.recvName"
                        class="font-bold text-#303133 ml-10px mr-20px"
                        >{{ activity.recvName }}</span
                      >
                      {{ activity.createTime }}
                    </div>
                    <div>
                      {{ activity.content }}
                    </div>
                    <!--                     附件-->
                    <div
                      v-if="activity.sysAttachFiles"
                      class="pb-10px"
                      style="border-bottom: 1px solid #e5e4ec"
                    >
                      <div
                        v-for="item in activity.sysAttachFiles"
                        :key="item.id"
                        class="inline-block"
                      >
                        <a
                          :href="item.url"
                          class="mr-10px text-#1890ff"
                          target="_blank"
                          >{{ item.origFileName }}</a
                        >
                      </div>
                    </div>
                    <div style="position: absolute; top: 12px; right: 4px">
                      <el-button
                        class="ml-30px"
                        icon="chatLineRound"
                        plain
                        size="small"
                        type="primary"
                        @click="handleReply('flowReply', activity)"
                        >回复
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
              <el-collapse-item name="1" title="传阅记录">
                <div class="block mt-20px">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(activity, index) in circulationList"
                      :key="index"
                      :timestamp="activity.createTime"
                      :type="'primary'"
                      placement="top"
                    >
                      <div>
                        {{ activity.createBy }}
                        <span class="ml-20px"
                          >传阅：{{ activity.assigneeName }}</span
                        >
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-col>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="查看流程" name="track">
        <!-- 高亮流程图 -->
        <my-process-viewer
          key="designer"
          v-model="xmlData"
          :activityData="activityList"
          :prefix="bpmnControlForm.prefix"
          :processInstanceData="processInstance"
          :taskData="tasks"
          :value="xmlData"
          v-bind="bpmnControlForm"
        />
      </el-tab-pane>
    </el-tabs>
    <!--加签表单-->
    <el-dialog v-model="signOpen" :title="signTitle" append-to-body width="700">
      <el-form
        ref="signForm"
        :model="taskHand"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="加签办理方式：" prop="countersignType">
          <el-radio-group
            v-model="taskHand.countersignType"
            style="width: 100px"
            @change="countersignTypeFn"
          >
            <el-radio label="1">加签人办理完成后，我再办理</el-radio>
            <el-radio label="2">加签人办理完成后，直接通过</el-radio>
            <el-radio label="3">一同处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="taskHand.countersignType == '2'">
          <el-form-item label="签署意见：" prop="comment">
            <el-input
              v-model="taskHand.comment"
              :rows="5"
              maxlength="300"
              placeholder="请输入签署意见"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="意见附件：">
            <el-upload
              v-model:file-list="taskHand.fileList"
              :before-upload="beforeAvatarUpload"
              :http-request="handleFileChange"
              :show-file-list="false"
              accept=".rar, .zip, .doc, .docx, .pdf"
              action="#"
              class="upload-demo"
            >
              <el-button style="font-size: 14px" type="default">
                <el-icon>
                  <UploadFilled />
                </el-icon>
                上传
              </el-button>
              <template #tip>
                <div class="el-upload__tip float-right">
                  支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                </div>
              </template>
            </el-upload>
            <div class="text-14px mt-10px" style="width: 100%">
              <div v-for="(item, index) in fileList" :key="item.fileId">
                <a :href="item.url" class="text-#409eff" target="_blank">{{
                  item.origFileName
                }}</a>
                <el-button plain text @click="delFileName(index)"
                  >删除
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="下一环节处理人" prop="countersignNextUserUUID">
            <el-select
              v-model="taskHand.countersignNextUserUUID"
              class="w-full"
              multiple
              placeholder="下一环节处理人"
              @focus="userInputFocus('countersignNextUserIds')"
            >
              <el-option
                v-for="(item, index) in selectOptionObj[
                  'countersignNextUserIds'
                ]"
                :key="index"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="taskHand.countersignType"
            label="抄送人：
            "
            prop="copyUserIdsUUID"
          >
            <el-select
              v-model="taskHand.copyUserIdsUUID"
              class="w-full"
              multiple
              placeholder="请选择抄送人"
              @focus="userInputFocus('copyUserIds')"
            >
              <el-option
                v-for="(item, index) in selectOptionObj['copyUserIds']"
                :key="index"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div
          v-if="
            taskHand.countersignType == '1' || taskHand.countersignType == '3'
          "
        >
          <el-form-item label="添加审批人：" prop="approverUUID">
            <el-select
              v-model="taskHand.approverUUID"
              class="w-full"
              multiple
              placeholder="请选择审批人
            "
              @focus="userInputFocus('approverIds')"
            >
              <el-option
                v-for="(item, index) in selectOptionObj['approverIds']"
                :key="index"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="加签意见：" prop="countersignComment">
            <el-input
              v-model="taskHand.countersignComment"
              :rows="5"
              maxlength="300"
              placeholder="请输入加签意见"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="footer dialog-footer text-right">
        <el-button
          @click="
            () => {
              signOpen = false
            }
          "
          >取 消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="submitSign"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!--流程表单-->
    <el-dialog
      v-model="returnOpen"
      :title="returnTitle"
      append-to-body
      width="700"
    >
      <el-form
        ref="taskForm"
        :model="taskHand"
        :rules="rules"
        label-width="140px"
      >
        <div v-if="returnTitle != '传阅'">
          <el-form-item
            :label="taskHand.type == 'flowReply' ? '内容：' : '签署意见：'"
            prop="comment"
          >
            <el-input
              v-model="taskHand.comment"
              :placeholder="
                taskHand.type == 'flowReply'
                  ? '请输入回复内容'
                  : '请输入签署意见'
              "
              :rows="5"
              maxlength="300"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="意见附件：">
            <el-upload
              v-model:file-list="taskHand.fileList"
              :before-upload="beforeAvatarUpload"
              :http-request="handleFileChange"
              :show-file-list="false"
              accept=".rar, .zip, .doc, .docx, .pdf"
              action="#"
              class="upload-demo"
            >
              <el-button style="font-size: 14px" type="default">
                <el-icon>
                  <UploadFilled />
                </el-icon>
                上传
              </el-button>
              <template #tip>
                <div class="el-upload__tip float-right">
                  支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                </div>
              </template>
            </el-upload>
            <div class="text-14px mt-10px" style="width: 100%">
              <div v-for="(item, index) in fileList" :key="item.fileId">
                <a :href="item.url" class="text-#409eff" target="_blank">{{
                  item.origFileName
                }}</a>
                <el-button plain text @click="delFileName(index)"
                  >删除
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            v-if="
              taskHand.taskName &&
              taskHand.type != 'reject' &&
              taskHand.type != 'return' &&
              taskHand.type != 'reply' &&
              taskHand.type != 'flowReply'
            "
            label="下一环节："
            prop="taskName"
          >
            <el-input v-model="taskHand.taskName" disabled type="input" />
          </el-form-item>
          <el-form-item
            v-if="taskHand.type == 'return'"
            label="退回节点："
            prop="targetKey"
          >
            <el-radio-group
              v-model="taskHand.targetKey"
              @change="returnTaskSelect"
            >
              <el-radio-button
                v-for="item in returnTaskList"
                :key="item.id"
                :label="item.id"
                >{{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="
              (taskHand.taskName || taskHand.type == 'return') &&
              taskHand.type != 'reject' &&
              taskHand.type != 'reply'
            "
            :label="
              taskHand.type == 'return'
                ? '退回节点处理人：'
                : '下一环节处理人：'
            "
            prop="nextUserIdsUUID"
          >
            <el-input
              v-if="appointUserName"
              v-model="taskHand.nextUserIdsUUID"
              disabled
              type="input"
            />
            <el-select
              v-else
              v-model="taskHand.nextUserIdsUUID"
              :disabled="taskHand.isSelset"
              :placeholder="
                JSON.stringify(taskHand.nextUserIdsUUID) != '[]'
                  ? ''
                  : taskHand.type == 'return'
                  ? '请选择退回节点处理人'
                  : '请选择下一环节处理人'
              "
              class="w-full"
              multiple
              @focus="userInputFocus('nextUserIds')"
            >
              <el-option
                v-for="(item, index) in selectOptionObj['nextUserIds']"
                :key="index"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item
          v-if="taskHand.type != 'reply' && taskHand.type != 'flowReply'"
          :label="returnTitle == '传阅' ? '传阅：' : '抄送：'"
          prop="copyUserIdsUUID"
        >
          <el-select
            v-model="taskHand.copyUserIdsUUID"
            :placeholder="returnTitle == '传阅' ? '请选择传阅' : '请选择抄送'"
            class="w-full"
            multiple
            @focus="userInputFocus('copyUserIds')"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['copyUserIds']"
              :key="index"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="taskHand.type == 'flowReply'"
          label=""
          prop="copyUserIdsUUID"
        >
          <el-checkbox v-model="replyRecvObj.informAllFlag"
            >提醒流程参与人
          </el-checkbox>
        </el-form-item>
      </el-form>

      <div class="footer dialog-footer text-right">
        <el-button
          @click="
            () => {
              returnOpen = false
            }
          "
          >取 消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="submitReturn"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 弹出框选择人员 下拉框 -->
    <SelectDialog
      :dialog-param="dialogParamUse"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>
  </div>
</template>

<script name="WorkDetail" setup>
import { ElLoading } from 'element-plus'
import { defineAsyncComponent, nextTick } from 'vue'
import { getDeptStaffTreeData } from '@/api/system/dept'
import {
  getPricipalId,
  getTreeNodeByParam,
  getUniqueUserId
} from '@/utils/commo'
import { useRoute, useRouter } from 'vue-router'
import { nextUserTask, getReturnPerson } from '@/api/workflow/model'
import myProcessViewer from '@/components/bpmnProcessDesigner/package/designer/ProcessViewer.vue'
import { detailProcess } from '@/api/workflow/process'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import {
  addComment,
  complete,
  addTask,
  delegate,
  transfer,
  rejectTask,
  returnList,
  returnTask,
  addCirculation,
  cyDetailList,
  addReply
} from '@/api/workflow/task'
import useTagsViewStore from '@/store/modules/tagsView'
import useCommonStore from '@/store/modules/common'
import { getNodeData } from '@/api/workflow/process'

const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const commentType = computed(() => {
  return val => {
    switch (val) {
      case '1':
        return '同意'
      case '2':
        return '不同意'
      case '3':
        return '驳回'
      case '4':
        return '委派'
      case '5':
        return '转办'
      case '6':
        return '终止'
      case '7':
        return '撤回'
      case '8':
        return '加签'
    }
  }
})
const approveTypeTag = computed(() => {
  return val => {
    switch (val) {
      case '1':
        return 'success'
      case '2':
        return 'warning'
      case '3':
        return 'danger'
      case '4':
        return 'primary'
      case '5':
        return 'success'
      case '6':
        return 'danger'
      case '7':
        return 'info'
    }
  }
})
const btnLoading = ref(false) //按钮加载状态
const data = reactive({
  height: document.documentElement.clientHeight - 205 + 'px;',
  // 模型xml数据
  loadIndex: 0,
  xmlData: undefined,
  historyProcNodeList: [],
  // 部门名称
  deptName: undefined,
  // 部门树选项
  deptOptions: undefined,
  userLoading: false,
  // 用户表格数据
  userList: null,
  deptProps: {
    children: 'children',
    label: 'label'
  },
  // 查询参数
  queryParams: {
    deptId: undefined
  },
  total: 0,
  // 遮罩层
  loading: true,
  taskForm: {
    comment: '', // 意见内容
    procInsId: '', // 流程实例编号
    taskId: '', // 流程任务编号
    copyUserIds: '', // 抄送Id
    vars: '',
    targetKey: '',
    copyUserIdsUUID: [],
    nextUserIdsUUID: []
  },
  rules: {
    taskName: [{ required: true, message: '', trigger: ['blur', 'change'] }],
    countersignType: computed(() =>
      signOpen.value
        ? [
            {
              required: true,
              message: '加签办理方式不能为空',
              trigger: ['blur', 'change']
            }
          ]
        : []
    ),
    countersignNextUserUUID: computed(() =>
      signOpen.value
        ? [
            {
              required: true,
              message: '下一环节处理人人不能为空',
              trigger: ['blur', 'change']
            }
          ]
        : []
    ),
    comment: [
      {
        required: true,
        message: '签署意见不能为空',
        trigger: ['blur', 'change']
      }
    ],
    nextUserIdsUUID: [
      {
        required: true,
        message: '该项不能为空',
        trigger: ['blur', 'change']
      }
    ],
    targetKey: [
      {
        required: true,
        message: '退回节点不能为空',
        trigger: ['blur', 'change']
      }
    ]
  },
  currentUserId: null,
  variables: [], // 流程变量数据
  processFormList: [], // 流程变量数据
  returnTaskList: [], // 回退列表数据
  processed: false,
  copyId: null, //是否是抄送
  returnTitle: null,
  returnOpen: false,
  rejectOpen: false,
  rejectTitle: null,
  taskRouteData: {} //业务关联
})
const {
  height,
  // 模型xml数据
  loadIndex,
  xmlData,
  historyProcNodeList,
  // 部门名称
  deptName,
  // 部门树选项
  deptOptions,
  userLoading,
  // 用户表格数据
  userList,
  deptProps,
  // 查询参数
  queryParams,
  total,
  loading,
  taskForm,
  rules,
  currentUserId,
  variables, // 流程变量数据
  processFormList, // 流程变量数据
  returnTaskList, // 回退列表数据
  copyId,
  processed,
  returnTitle,
  returnOpen,
  rejectOpen,
  rejectTitle,
  taskRouteData
} = toRefs(data)
const taskHand = ref({
  comment: '', // 意见内容
  procInsId: '', // 流程实例编号
  taskId: '', // 流程任务编号
  copyUserIds: '', // 抄送Id
  vars: '',
  targetKey: '',
  copyUserIdsUUID: [],
  nextUserIdsUUID: [],
  //加签
  countersignComment: '',
  countersignType: '',
  approverUUID: [],
  approverIds: '',
  countersignNextUserIds: '',
  countersignNextUserUUID: []
}) //表单
const isComponent = ref('') //动态组件名
let deptUserData = [] //获取人员的数据
// 获取tab分标签高亮
const activeName = ref('businness')
const flowUseData = ref([]) //设计模型中设置了岗位 获取岗位的人
const appointUserName = ref(null) //绩效特点指定人
const signDisabled = ref(false) //是否禁止加签
const completion = ref(null) //是否办结-发布 ==按钮名称
const otherApprovals = ref(null) //是否走其他审批-审批按钮名称
const circulationList = ref([]) //传阅
const isCirculation = ref(false) //是否显示传阅
const orderReverse = ref(true) //意见查看记录顺序 true倒叙 false 正序
// 获取路由上的信息
function initData() {
  orderReverse.value =
    localStorage.getItem('orderReverse') == 'true' ? true : false //记录顺序
  taskHand.value.procInsId = route.query && route.query.procInsId
  taskHand.value.taskId = route.query && route.query.taskId
  processed.value = route.query && eval(route.query.processed || false)
  isCirculation.value = route.query && eval(route.query.isCirculation || false)
  copyId.value = (route.query && route.query.copyId) || null
  // 流程任务重获取变量表单
  getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
  loadIndex.value = taskHand.value.procInsId
}

/** 切换顺便模块 start*/
const eleRefs = ref(null)
/**切换记录顺序*/
const orderReverseFn = e => {
  localStorage.setItem('orderReverse', e)
  historyProcNodeList.value =
    historyProcNodeList.value && historyProcNodeList.value.length > 0
      ? historyProcNodeList.value.reverse()
      : []
  if (!orderReverse.value && eleRefs.value) {
    nextTick(() => {
      //自动固定底部
      eleRefs.value.scrollIntoView({ behavior: 'smooth', block: 'end' })
    })
  }
}
const handleChangeTab = e => {
  console.log(orderReverse.value, e, eleRefs.value, '111')
  if (e != 'record') {
    return false
  }
  if (orderReverse.value == false && eleRefs.value) {
    nextTick(() => {
      console.log('滚动--')
      //自动固定底部
      eleRefs.value.scrollIntoView({ behavior: 'smooth', block: 'end' })
    })
  }
}

/** 切换顺序模块 end */
function setIcon(val) {
  if (val) {
    return 'el-icon-check'
  } else {
    return 'el-icon-time'
  }
}

function setColor(val) {
  if (val) {
    return '#2bc418'
  } else {
    return '#b3bdbb'
  }
}

// ========== 高亮流程图 start ==========
const bpmnControlForm = ref({
  prefix: 'flowable'
})
const activityList = ref([]) //高亮的流程
const processInstance = ref({}) //可展示流程发起人等信息
const tasks = ref([]) //每个节点鼠标以上去显示的 可展示 UserTask 审核相关的信息
// ========== 高亮流程图 end ==========

/**
 *
 * @param {*} arrMenus  传入的数组或者树数据 例 treeData
 * @param {*} val 对比的值 例 1
 */
function dealTreeOnceChecked(arrMenus, val) {
  if (arrMenus.length > 0) {
    arrMenus.forEach(item => {
      if (item.id == val) {
        item.disabled = true
      } else {
        let arrChildren = item.children
        if (arrChildren != null) {
          dealTreeOnceChecked(arrChildren, val)
        }
      }
    })
  }
}

/**根据当前用户回填下一环节处理人 抄送人
 *
 * @param {*} idArr  是对应id值
 * @param {*} type  type 类型 ban 已有抄送人（针对抄送人）  post 指定人岗位
 * @param {*} data  数据源
 * @param {*} isDisabled 回填值不能删除
 * @returns {*
 * selectData  选中的数据集合
 * uuid 选中的uuid
 * ids val值得字符串根式
 * copyData 处理后的源数据
 * }
 */
function getDefaultUserInfo(idArr, type, data, isDisabled) {
  if (!idArr || JSON.stringify(idArr) == '[]') {
    return false
  }
  let uuid = [], //获取uuid
    textArr = [], //获取选中的文字
    selectData = [] //获取数据源
  if (type == 'ban') {
    let deptUserData2 = JSON.parse(JSON.stringify(deptUserData))
    //获取名称
    idArr.map(item => {
      dealTreeOnceChecked(deptUserData2, item) // 已经有的抄送人 不能删除
      let res = getTreeNodeByParam(deptUserData, item, 'id', [])
      if (res.length > 0) {
        selectData.push({ ...res[0], disabled: true })
        uuid.push(res[0].uuid)
      }
    })
    return {
      copyData: deptUserData2,
      val: uuid,
      ids: idArr,
      selectData: selectData
    }
  } else if (type == 'post') {
    let dataCollation = JSON.parse(JSON.stringify(data))
    //岗位的情况
    idArr.map(item => {
      if (isDisabled) {
        dealTreeOnceChecked(dataCollation, item) // 已经选中的人 不能删除
      }
      let res = getTreeNodeByParam(data, item, 'id', [])
      if (res.length > 0) {
        if (isDisabled) {
          selectData.push({ ...res[0], disabled: true })
        } else {
          selectData.push(res[0])
        }
        uuid.push(res[0].uuid)
      }
    })
    return {
      val: uuid,
      ids: idArr.toString(),
      selectData: selectData,
      DataDisabled: dataCollation
    }
  } else {
    // 获取id
    idArr.map(item => {
      let res = getTreeNodeByParam(deptUserData, item, 'id', [])
      if (res.length > 0) {
        if (isDisabled) {
          selectData.push({ ...res[0], disabled: true })
        } else {
          selectData.push(res[0])
        }
        uuid.push(res[0].uuid)
      }
    })
    return { val: uuid, ids: idArr.toString(), selectData: selectData }
  }
}

// 获取抄送人 下一环节人的初始化数据
const getHandleUsers = async type => {
  if (processed.value) {
    //获取抄送人 下一环节人的初始化数据
    let res = await nextUserTask(taskHand.value.taskId, {
      isCompletion: clickBtnType.value === 'completion' ? 'Y' : 'N',
      isOtherApprovals: clickBtnType.value === 'otherApprovals' ? 'Y' : 'N'
    })
    // 已抄送人
    taskHand.value.existedCopyUsers = res.data.copyData //已经存在的数据 不能在传给后端
    appointUserName.value = null
    if (res.data.copyData && res.data.copyData.length > 0) {
      let { selectData, val, ids, copyData } = getDefaultUserInfo(
        res.data.copyData,
        'ban'
      )
      selectOptionObj.value['copyUserIds'] = selectData
      taskHand.value.copyUserIdsUUID = val
      taskHand.value.copyUserIds = ids
      taskHand.value.copyData = copyData
    }
    if (res.data.taskData && res.data.taskData.length > 0) {
      taskHand.value.taskName = res.data.taskData[0].taskName
      // 1. 下一环节处理人分析
      // 1 会签（流程中有A,B人，A指定下一环节人c,B指定下一环节人D） readyUser 已经存在指定人
      let readyUser = res.data.readyUser
        ? res.data.readyUser.split(',').map(Number)
        : []
      if (res.data.taskData[0].hasUser) {
        // 1.1 设计模型里设置指定人 ---- 下一环节 下一环节处理人 有存在下一环节人时 说明走固定模式不能更改
        let hasUser = res.data.taskData[0].hasUser.split(',').map(Number)
        let { selectData, val, ids } = getDefaultUserInfo(hasUser)
        selectOptionObj.value['nextUserIds'] = selectData
        taskHand.value.nextUserIdsUUID = val
        taskHand.value.nextUserIds = ids
        taskHand.value.isSelset = true
      } else if (res.data.taskData[0].postUser) {
        //1.2 设计模型里设置岗位
        let postRes = await getDeptStaffTreeData({
          userIds: res.data.taskData[0].postUser,
          deptId: 484
        })
        let postIds = res.data.taskData[0].postUser.split(',')
        if (postIds.length == 1) {
          //1.2.1 如果该岗位下只有一个用户的时候 默认选中
          let { selectData, val, ids } = getDefaultUserInfo(
            postIds,
            'post',
            postRes.data
          )
          selectOptionObj.value['nextUserIds'] = selectData
          taskHand.value.nextUserIdsUUID = val
          taskHand.value.nextUserIds = ids
          taskHand.value.isSelset = true
        } else {
          //获取该岗位下的下一环节处理人
          if (readyUser.length > 0) {
            //有指定人的情况下
            let { selectData, val, ids, DataDisabled } = getDefaultUserInfo(
              readyUser,
              'post',
              postRes.data,
              true
            )
            selectOptionObj.value['nextUserIds'] = selectData
            flowUseData.value = DataDisabled
            taskHand.value.nextUserIdsUUID = val
            taskHand.value.nextUserIds = ids
            taskHand.value.isSelset = false
          } else {
            flowUseData.value = postRes.data
            taskHand.value.isSelset = false
            taskHand.value.nextUserIdsUUID = []
            taskHand.value.nextUserIds = null
          }
        }
      } else if (
        res.data.taskData[0].appointUserId &&
        res.data.taskData[0].appointUserName
      ) {
        //1.3 绩效业务情况下，指定下一环节人
        taskHand.value.nextUserIds = res.data.taskData[0].appointUserId
        appointUserName.value = res.data.taskData[0].appointUserName
        taskHand.value.nextUserIdsUUID = res.data.taskData[0].appointUserName
      } else {
        //1.4 没有下一环节处理人
        taskHand.value.nextUserIdsUUID = []
        taskHand.value.nextUserIds = null
        taskHand.value.isSelset = false
      }
    } else {
      taskHand.value.taskName = null
    }
    // 1. 获取退回节点人的数据列表
    if (type == 'return') {
      getReturnHandleUsers()
    }
  }
}
/**
 * 获取退回节点人的数据列表
 * @param {*} type
 */
const getReturnHandleUsers = async () => {
  appointUserName.value = null
  // 1.2 获取退回节点的人员
  let returnRes = await getReturnPerson({
    procInsId: taskHand.value.procInsId,
    targetKey: taskHand.value.targetKey
  })
  if (returnRes.data.appointUserId && returnRes.data.appointUserName) {
    //1.3 绩效业务情况下，指定下一环节人
    taskHand.value.nextUserIds = returnRes.data.appointUserId
    appointUserName.value = returnRes.data.appointUserName
    taskHand.value.nextUserIdsUUID = returnRes.data.appointUserName
    return false
  }
  //1.2 获取人员的数组
  let postRes = await getDeptStaffTreeData({
    userIds: returnRes.data.assignee,
    deptId: 484
  })
  let postIds = returnRes.data.assignee.split(',')
  if (postIds.length == 1) {
    //1.2.1 如果该岗位下只有一个用户的时候 默认选中
    let { selectData, val, ids } = getDefaultUserInfo(
      postIds,
      'post',
      postRes.data
    )
    console.log(selectData, val, ids, 'selectData, val, ids ')
    selectOptionObj.value['nextUserIds'] = selectData
    taskHand.value.nextUserIdsUUID = val
    taskHand.value.nextUserIds = ids
    taskHand.value.isSelset = true
  } else {
    //获取该岗位下的下一环节处理人
    flowUseData.value = postRes.data
    taskHand.value.isSelset = false
    taskHand.value.nextUserIdsUUID = []
    taskHand.value.nextUserIds = null
  }
}
/**
 * 退回节点选择
 */
const returnTaskSelect = async () => {
  await getReturnHandleUsers()
}

/*** 获取详情数据 */
async function getProcessDetails(procInsId, taskId) {
  const params = { procInsId: procInsId, taskId: taskId }
  // 全部人员接口
  deptUserData = await commonStore.getUseTreeData()
  // 获取流程详情接口
  let res = await detailProcess(params)
  const data = res.data
  xmlData.value = data.bpmnXml
  processFormList.value = data.processFormList
  historyProcNodeList.value =
    orderReverse.value == false &&
    data.historyProcNodeList &&
    data.historyProcNodeList.length > 0
      ? data.historyProcNodeList.reverse()
      : data.historyProcNodeList
  activityList.value = data.historyProcNodeList
  const urls = data.taskRouteData.routeKey.toString()
  isComponent.value = initComponents(urls)
  taskHand.value.variables = {
    businessId: data.taskRouteData.businessId.toString()
  }
  taskRouteData.value = {
    businessId: data.taskRouteData.businessId.toString()
  }
  //获取当前流程节点 是否禁止加签
  let flowRes = await getNodeData(data.taskRouteData.businessId.toString())
  signDisabled.value = flowRes.data?.signDisabled
  //是否办结 或发布==按钮名称
  completion.value = flowRes.data.completion ? flowRes.data.completion : null
  //是否走其他审批-审批按钮名称
  otherApprovals.value = flowRes.data.otherApprovals
    ? flowRes.data.otherApprovals
    : null
  await getCyDetailList(data.taskRouteData.businessId.toString())
  await getReturnList()
}

const replyList = ref([]) //回复列表
// 获取传阅的记录
const getCyDetailList = async id => {
  let cyRes = await cyDetailList({ businessId: id })
  // 传阅
  const newData =
    cyRes.data && cyRes.data.cyList
      ? JSON.parse(JSON.stringify(cyRes.data.cyList))
      : []
  let mergedArr = []
  if (newData.length > 0) {
    mergedArr = newData.reduce((acc, curr) => {
      const existingItem = acc.find(
        item =>
          item.createTime === curr.createTime && item.createBy === curr.createBy
      )
      if (existingItem) {
        existingItem.assigneeName += `,${curr.assigneeName}`
        existingItem.id += `,${curr.id}`
        existingItem.assignee += `,${curr.assignee}`
      } else {
        acc.push(curr)
      }
      return acc
    }, [])
  }
  circulationList.value = mergedArr
  replyList.value = cyRes.data.hfList
}
// ========== 动态注册组件 start ==========
const initComponents = url => {
  const modules = import.meta.glob([
    // '@/views/**/**detail.vue',
    // '@/views/**/**Details.vue',
    // '@/views/**/**Details/index.vue',
    '@/views/**/**edit**/index.vue',
    '@/views/**/**edit**.vue',
    '@/views/**/**Edit.vue',
    '@/views/**/**Edit**.vue',
    '@/views/**/edit**.vue',
    '@/views/**/contactsAddOrUpdate/index.vue',
    '@/views/**/customerAddOrUpdate/index.vue',
    '@/views/**/downloadApprove/index.vue',
    '@/views/**/**Form.vue',
    '@/views/**/biddingResults.vue',
    '@/views/rsgl/workOrder/module/orderFrom.vue',
    '@/views/**/add**/index.vue'
  ])
  const link = modules[`/src/views/${url}.vue`]
  return markRaw(defineAsyncComponent(link))
}
// ========== 动态注册组件 end ==========
// ========== 加签 start ==========
const signTitle = ref('')
const signOpen = ref(false)

/** 加签 */
async function handleCountersign() {
  returnOpenFn()
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers()
  proxy.resetForm('signForm')
  signTitle.value = '加签'
  signOpen.value = true
}

// 加签办理方式
const countersignTypeFn = val => {}

/** 流程弹出框 确认按钮 */
function submitSign() {
  console.log(
    taskHand.value.countersignType,
    taskHand.value,
    'taskHand.countersignType=='
  )
  proxy.$refs['signForm'].validate(valid => {
    console.log(valid, 'valid')
    if (valid) {
      let param = {}
      if (taskHand.value.countersignType == '2') {
        param = handleQuery(taskHand.value)
        param.variables.isCompletion =
          clickBtnType.value === 'completion' ? 'Y' : 'N'
        param.variables.isOtherApprovals =
          clickBtnType.value === 'otherApprovals' ? 'Y' : 'N'
        param.nextUserIds = taskHand.value.countersignNextUserIds?.toString()
      } else {
        param = {
          taskId: taskHand.value.taskId,
          comment: '加签 ' + taskHand.value.countersignComment,
          assignee: taskHand.value.approverIds?.toString()
        }
      }
      if (taskHand.value.countersignType == '1') {
        //委派任务-改成加签任务-加签任务（返回）/加签人办理完成后，我在办理
        delegate(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
          })
          .catch(error => {
            btnLoading.value = false
          })
      } else if (taskHand.value.countersignType == '2') {
        //委派任务-改成加签任务-加签任务（返回）/加签人办理完成后，我在办理
        transfer(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
          })
          .catch(error => {
            btnLoading.value = false
          })
      } else {
        addTask(param)
          .then(response => {
            proxy.$modal.msgSuccess('操作成功')
            signOpen.value = false
            btnLoading.value = false
            getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
          })
          .catch(error => {
            btnLoading.value = false
          })
      }
    }
  })
}

// ========== 加签 end ==========
/** 回复 */
const replyRecvObj = ref({
  recvId: null,
  recvName: null,
  informAllFlag: 0
}) //接收人id
async function handleReply(type, row) {
  returnOpenFn()
  returnTitle.value = '回复'
  taskHand.value.type = type
  taskHand.value.comment = type == 'reply' ? '已阅' : undefined
  if (row) {
    replyRecvObj.value.recvId = row.assigneeId || row.assignee || row.sendId
    replyRecvObj.value.recvName = row.assigneeName || row.sendName
  } else {
    replyRecvObj.value.recvId = null
    replyRecvObj.value.recvName = null
  }
  console.log(row, 'row---', replyRecvObj.value)
  returnOpen.value = true
}

const chindRef = ref(null)
const clickBtnType = ref() // 点击按钮类型 -- 同意 办结（completion） 提交审批（otherApprovals）
/** 通过/同意任务 */
async function handleComplete(type) {
  if (type == 'circulation') {
    returnTitle.value = '传阅'
    taskHand.value.type = 'circulation'
    selectOptionObj.value['copyUserIds'] = []
    taskHand.value.copyUserIdsUUID = []
    taskHand.value.copyUserIds = ''
    taskHand.value.copyData = []
    returnOpen.value = true
    return false
  }
  clickBtnType.value = type
  let errorMsg = null
  try {
    await proxy.$refs['chindRef'].handleSave()
    errorMsg = null
  } catch (error) {
    const { name, message } = error
    errorMsg = message
    console.log('同意/提交 按钮=错误==》', error)
  }
  console.log(errorMsg, 'errorMsg')
  if (
    errorMsg &&
    errorMsg.indexOf('proxy.$refs.chindRef.handleSave is not a function') == -1
  ) {
    return false
  }
  returnOpenFn()
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers()
  returnTitle.value = '同意'
  taskHand.value.type = 'complete'
  if (
    (type == 'agree' && returnTaskList.length != 0) ||
    type == 'otherApprovals'
  ) {
    taskHand.value.comment = '同意'
  } else {
    taskHand.value.comment = undefined
  }

  returnOpen.value = true
}

/** 拒绝任务 */
async function handleReject() {
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers()
  returnTitle.value = '拒绝审批单'
  taskHand.value.type = 'reject'
  returnOpen.value = true
}

/** 返回页面 */
function goBack() {
  router.go(-1)
  useTagsViewStore().delView(router.currentRoute.value)
}

/** 获取退回列表 */
async function getReturnList() {
  if (!processed.value) {
    returnTaskList.value = []
    return false
  }
  let newParams = handleQuery(taskHand.value)
  let res = await returnList(newParams) //获取退回的节点数据
  if (res.data && res.data.length == 0) {
    returnTaskList.value = []
    return false
  }
  returnTaskList.value = res.data
  taskHand.value.values = null
  taskHand.value.targetKey =
    res.data && res.data.length > 0 ? res.data[res.data.length - 1].id : ''
}

/** 可退回、不同意任务列表 */
async function handleReturn() {
  returnTitle.value = '不同意'
  taskHand.value.type = 'return'

  returnOpenFn()
  // 获取抄送人 下一环节人的初始化数据
  await getHandleUsers('return')
  returnOpen.value = true
  taskHand.value.comment = '不同意'
}

/**
 *
 js比较两个数组,取出不同的值
 */
const getDiff = (arr1, arr2) => {
  arr1 = JSON.stringify(arr1) == '[]' || !arr1 ? [] : arr1
  arr2 = JSON.stringify(arr2) == '[]' || !arr2 ? [] : arr2
  return [
    ...arr1.filter(item => !arr2.includes(item)),
    ...arr2.filter(item => !arr1.includes(item))
  ]
}
/**
 * 处理参数
 * @param {*} obj
 */
const handleQuery = obj => {
  let params = JSON.parse(JSON.stringify(obj))
  let copyUserIds = getDiff(obj.copyUserIds, toRaw(obj.existedCopyUsers))
  params.copyUserIds = copyUserIds ? copyUserIds.toString() : ''
  params.attachments = fileList.value
  delete params.fileList
  delete params.existedCopyUsers
  delete params.nextUserIdsUUID
  delete params.copyUserIdsUUID
  delete params.type
  delete params.copyData
  delete params.taskName
  delete params.isSelset
  delete params.approverIds
  delete params.approverUUID
  delete params.countersignComment
  delete params.countersignType
  delete params.countersignNextUserIds
  delete params.countersignNextUserUUID

  return params
}

/** 流程弹出框 确认按钮 */
function submitReturn() {
  proxy.$refs['taskForm'].validate(valid => {
    if (valid) {
      let newParams = handleQuery(taskHand.value)
      const fileName = []
      if (fileList.value) {
        fileList.value.map((val, curr) => {
          fileName.push(val.fileName)
        })
      }
      switch (taskHand.value.type) {
        case 'flowReply':
          if (fileName.length > 5) {
            proxy.$modal.msgError('文件个数不能超过5')
            return false
          }
          //流程中回复
          btnLoading.value = true
          const informAllFlag = replyRecvObj.value.informAllFlag == true ? 1 : 0
          console.log(informAllFlag, replyRecvObj.value, 'replyRecvObj.value--')
          let flowParams = {
            businessId: taskHand.value.variables.businessId, //业务id
            recvId: informAllFlag == 1 ? '' : replyRecvObj.value.recvId, //接收人id
            recvName: informAllFlag == 1 ? '' : replyRecvObj.value.recvName, //接收人名称
            fileNames: fileName, //文件
            content: taskHand.value.comment,
            procInsId: taskHand.value.procInsId,
            informAllFlag: informAllFlag //通知全体人员标志
          }
          addReply(flowParams)
            .then(response => {
              proxy.$modal.msgSuccess('操作成功')
              returnOpen.value = false
              getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'reply':
          // 审批中回复
          btnLoading.value = true
          let params = {
            copyId: copyId.value,
            attachments: fileList.value,
            comment: taskHand.value.comment,
            procInsId: taskHand.value.procInsId,
            taskId: taskHand.value.taskId
          }
          console.log(newParams, 'newParams--')
          addComment(params)
            .then(response => {
              proxy.$modal.msgSuccess('操作成功')
              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'complete':
          btnLoading.value = true
          newParams.variables.isCompletion =
            clickBtnType.value === 'completion' ? 'Y' : 'N'
          newParams.variables.isOtherApprovals =
            clickBtnType.value === 'otherApprovals' ? 'Y' : 'N'
          console.log(newParams, 'newParams--')
          // complete(newParams, 1)
          //   .then(response => {
          //     proxy.$modal.msgSuccess('操作成功')
          //     goBack()
          //     returnOpen.value = false
          //     btnLoading.value = false
          //   })
          //   .catch(error => {
          //     btnLoading.value = false
          //   })
          break
        case 'reject':
          proxy.$modal
            .confirm('拒绝审批单流程会终止，是否继续？')
            .then(function () {
              return rejectTask(newParams)
            })
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')
              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'return':
          // 退回
          btnLoading.value = true
          returnTask(newParams)
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')

              goBack()
              returnOpen.value = false
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
        case 'circulation':
          // 传阅
          btnLoading.value = true
          let param = {}
          param.assignee = newParams.copyUserIds
          param.procInsId = newParams.procInsId
          param.variables = newParams.variables
          param.messageTitle = '传阅'
          addCirculation(param)
            .then(res => {
              proxy.$modal.msgSuccess('操作成功')
              returnOpen.value = false
              getProcessDetails(taskHand.value.procInsId, taskHand.value.taskId)
              btnLoading.value = false
            })
            .catch(error => {
              btnLoading.value = false
            })
          break
      }
    }
  })
}

/**流程表单
 * 弹出框 取消
 */
const returnOpenFn = () => {
  appointUserName.value = null
  taskHand.value.fileList = []
  fileList.value = []
  taskHand.value.comment = ''
  taskHand.value.copyUserIds = ''
  taskHand.value.copyUserIdsUUID = []
  taskHand.value.nextUserIdsUUID = []
  //加签
  taskHand.value.countersignComment = ''
  taskHand.value.countersignType = ''
  taskHand.value.approverUUID = []
  taskHand.value.approverIds = ''
  taskHand.value.countersignNextUserIds = ''
  taskHand.value.countersignNextUserUUID = []
  replyRecvObj.value.informAllFlag = false
  proxy.resetForm('taskForm')
}
/*************************** 文件上传 start ****/
let fileList = ref([])

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

/************************** 文件上传 end */
/************************** 选择人 模块 start */
const dialogParamUse = ref({})
const selectOptionObj = ref({})

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus(type) {
  dialogParamUse.value = {
    type: type,
    title: '请选择人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
  }
  if (
    type == 'copyUserIds' &&
    taskHand.value.copyData &&
    JSON.stringify(taskHand.value.copyData) != '[]'
  ) {
    //已抄送人
    dialogParamUse.value.dataType = 'copyUser'
    dialogParamUse.value.data = taskHand.value.copyData
    dialogParamUse.value.defaultCheckedKeys = taskHand.value.copyUserIdsUUID
  }
  if (type == 'nextUserIds' && toRaw(flowUseData.value).length >= 1) {
    //下一个环节处理人-岗位多人的情况下
    dialogParamUse.value.data = flowUseData.value
    dialogParamUse.value.defaultCheckedKeys = taskHand.value.nextUserIdsUUID
  }
  if (type == 'approverIds') {
    //添加审批人
    dialogParamUse.value.defaultCheckedKeys = taskHand.value.approverUUID
  }
  if (type == 'countersignNextUserIds') {
    //添加审批人
    dialogParamUse.value.defaultCheckedKeys =
      taskHand.value.countersignNextUserUUID
  }

  dialogParamUse.value.isDialog = true
}

/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'nextUserIds':
      //下一个环节处理人
      selectOptionObj.value['nextUserIds'] = val.selectData
      taskHand.value.nextUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.nextUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['nextUserIds'],
            val.defaultCheckedKeys
          ).toString()
        : null
      break
    case 'copyUserIds':
      //抄送人
      selectOptionObj.value['copyUserIds'] = val.selectData
      taskHand.value.copyUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.copyUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['copyUserIds'],
            val.defaultCheckedKeys
          )
        : null
      break
    case 'approverIds':
      //加签-添加审批人
      selectOptionObj.value['approverIds'] = val.selectData
      taskHand.value.approverUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.approverIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['approverIds'],
            val.defaultCheckedKeys
          )
        : null
      taskHand.value.countersignComment = '审批人：' + val.labelData?.toString()
      break
    case 'countersignNextUserIds':
      //加签-添加下一环节出来人
      selectOptionObj.value['countersignNextUserIds'] = val.selectData
      taskHand.value.countersignNextUserUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.countersignNextUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['countersignNextUserIds'],
            val.defaultCheckedKeys
          )
        : null
      break
  }
}
const closeFn = val => {
  dialogParamUse.value.isDialog = false
}
/************************** 选择人 模块 end */
watch(
  () => route,
  (newVal, oldVal) => {
    if (location.href.match(/workDetail/)) {
      initData()
      activeName.value = 'businness'
    }
  },
  {
    // deep: true,
    immediate: true
  }
)
/******************************* 项目负责人 模块 end */
</script>
<style>
.workDetail .el-timeline-item__content .el-card__body {
  padding: 15px 20px 15px 20px !important;
}
</style>
<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';

:deep(.workDetail-tabs .el-tabs__header) {
  position: fixed;
  width: 100%;
  bottom: 0px;
  z-index: 333;
}

:deep(.el-tabs__content) {
  padding: 0 0 50px;
  border: none;
}

:deep(.el-tabs--border-card) {
  border: none;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  color: #ffffff;
  background-color: #1890ff;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  color: #1890ff;
}

:deep(.el-tab-pane > .el-card) {
  border: none;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.button-new-tag {
  margin-left: 10px;
}
</style>
